
package com.wifipositioner.wifi;

import java.util.ArrayList;
import java.util.List;

import android.app.PendingIntent.OnFinished;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;

import com.wifipositioner.activity.WifipositionerActivity;

public class WifiProvider {
	
	private static WifiProvider instance = null;
	
	private static WifiManager wifiManager;
	
	private ArrayList<Handler> registredHandlers;
	
	private BroadcastReceiver broadcastReceiver;
	
	private WifiProvider() {
		wifiManager = (WifiManager) WifipositionerActivity.context
										.getSystemService(Context.WIFI_SERVICE);
		registredHandlers = new ArrayList<Handler>();
		broadcastReceiver = new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context context, Intent intent) {
				List<ScanResult> scanResult = wifiManager.getScanResults();
				for(Handler handler : registredHandlers){
					Message msg = new Message();
					msg.obj = scanResult;
					handler.sendMessage(msg);
				}
				
			}
		};
		
		WifipositionerActivity.context.registerReceiver(broadcastReceiver, 
				new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
		
	}
	
	public static WifiProvider get(){
		if(instance == null){
			instance = new WifiProvider();
			return instance;
		}
		else{
			return instance;
		}
	}
	public void registerHandler(Handler handler){
		registredHandlers.add(handler);
	}
	public void removeHandler(Handler handler){
		registredHandlers.remove(handler);
	}
	public void scan(){
		wifiManager.startScan();
	} 
	public void unregisterReciever(){
		WifipositionerActivity.context.unregisterReceiver(broadcastReceiver);
	}

	
}
